package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.utils.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderDetailService;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.rabbit.constant.RabbitConst;
import com.atguigu.gmall.rabbit.service.RabbitService;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    @Qualifier("redis")
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RabbitService rabbitService;

    @GetMapping("/auth/trade")
    public Map<String,Object> trade(){
            Map<String,Object> tradeMap = new HashMap<>();
            //用户地址信息
            List<UserAddress> userAddressList = userFeignClient.getUserAddressList();
            tradeMap.put("userAddressList",userAddressList);
            //购物车信息
            List<CartInfo> isCheckCartList = cartFeignClient.getIsCheckCartList();
            List<OrderDetail> orderDetailList = new ArrayList<>();
            isCheckCartList.forEach(cartInfo -> {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                orderDetail.setOrderPrice(cartInfo.getSkuPrice());
                orderDetail.setSkuId(cartInfo.getSkuId());
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setSkuNum(cartInfo.getSkuNum());
                orderDetailList.add(orderDetail);
            });
            tradeMap.put("detailArrayList",orderDetailList);
            //计算总商品件数
            long totalNum = orderDetailList.stream().collect(Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
            tradeMap.put("totalNum",totalNum);
            //计算总金额
            BigDecimal totalAmount = new BigDecimal("0");
            for (OrderDetail orderDetail : orderDetailList) {
                totalAmount = totalAmount.add(orderDetail.getOrderPrice().multiply(new BigDecimal(orderDetail.getSkuNum())));
            }
            tradeMap.put("totalAmount",totalAmount);
            //生成订单号
            String tradeNO = UUID.randomUUID().toString().replaceAll("-", "");
            ServletRequestAttributes  requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            String userId = AuthContextHolder.getUserId(request);
            redisTemplate.opsForValue().set(RedisConst.USER_KEY_PREFIX+userId+RedisConst.TRADENO,tradeNO);
            tradeMap.put("tradeNo",tradeNO);
            return tradeMap;
    }

    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,
                              String tradeNo,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //使用交易号防止二次提交
        Object redisTradeNo = redisTemplate.opsForValue().get(RedisConst.USER_KEY_PREFIX + userId + RedisConst.TRADENO);
        if(redisTradeNo!=null){
            if(!redisTradeNo.equals(tradeNo)){
                return Result.fail().message("非法操作");
            }else{
                redisTemplate.delete(RedisConst.USER_KEY_PREFIX + userId + RedisConst.TRADENO);
            }
        }else{
            return Result.fail().message("不要重复提交");
        }
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            boolean isHasStock = orderInfoService.hasStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
            if(!isHasStock){
                return Result.fail().message(orderDetail.getSkuName()+"无货");
            }
        }

        //提交订单
        Long orderId = orderInfoService.addOrderInfo(orderInfo,userId);
        rabbitService.sendMessage(RabbitConst.EXCHANGE_DEAD,RabbitConst.ROUTING_DEAD_1,orderId);
        return Result.ok(orderId);
    }

    //订单信息
    @GetMapping("/auth/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
        return orderInfo;
    }

    //拆单[{"wareId":"1","skuIds":["2"]},{"wareId":"2","skuIds":["1"]}]
    @PostMapping("/orderSplit")
    public String orderSplit(Long orderId,String wareSkuMap){
        System.out.println(wareSkuMap);
        List<OrderInfo> orderSplitMapList = orderInfoService.orderSplit(orderId,wareSkuMap);
        return JSONObject.toJSONString(orderSplitMapList);
    }
    @PostMapping("inner/seckill/submitOrder")
    public Long submitOrder(@RequestBody OrderInfo orderInfo) {
        Long orderId = orderInfoService.addOrderInfo(orderInfo,"1");
        return orderId;
    }


}
